package com.gmlive.common.sample.alert_permission

import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import androidx.annotation.RequiresApi
import com.gmlive.common.ui.systembartint.OSUtil

/**
 *
 * @Author Sven
 * @Date 2021/8/5
 * @Email jiangzhimin@inke.cn
 */
class SettingsCompat private constructor(private val delegate: ISettings) {

    companion object {
        @Volatile
        private var _instance: SettingsCompat? = null

        val instance: SettingsCompat
            get() =
                _instance ?: synchronized(this) {
                    _instance ?: SettingsCompat(getDelegate()).also { _instance = it }
                }


        private fun getDelegate(): ISettings {
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
                Build.VERSION.SDK_INT < Build.VERSION_CODES.O
            ) {
                if (OSUtil.isVivo()) {
                    SettingsVIVO()
                } else {
                    SettingAfterM()
                }
            } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                SettingsBelowM()
            } else {
                SettingAfterM()
            }
        }
    }

    fun canDrawOverlays(context: Context): Boolean {
        return delegate.canDrawOverlays(context)
    }

    fun requestPermission(context: Context) {
        delegate.requestPermission(context)
    }

    private class SettingsBelowM : ISettings {
        override fun canDrawOverlays(context: Context): Boolean = true

        override fun requestPermission(context: Context) {
        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    private class SettingAfterM : ISettings {
        override fun canDrawOverlays(context: Context): Boolean {
            return Settings.canDrawOverlays(context)
        }

        override fun requestPermission(context: Context) {
            val intent = Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:" + context.packageName)
            )
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }
    }

    private class SettingsVIVO : ISettings {
        private val allowContentUri =
            Uri.parse("content://com.iqoo.secure.provider.secureprovider/allowfloatwindowapp")
        private val floatContentUri =
            Uri.parse("content://com.vivo.permissionmanager.provider.permission/float_window_apps")
        private val allowProjection = arrayOf("currentlmode")
        private val floatProjection = arrayOf("currentmode")
        private val selection = "pkgname = ?"

        @RequiresApi(Build.VERSION_CODES.M)
        override fun canDrawOverlays(context: Context): Boolean {
            val selectionArgs = arrayOf(context.packageName)

            var allowMode = 1
            var checkNext = false
            var cursor: Cursor? = null
            try {
                cursor = context.contentResolver.query(
                    allowContentUri,
                    allowProjection,
                    selection,
                    selectionArgs,
                    null
                )
                if (cursor?.moveToFirst() == true) {
                    checkNext = false
                    allowMode = cursor.getInt(0)
                } else {
                    checkNext = true
                }
            } catch (ex: Exception) {
                checkNext = true
                Log.i("SettingsCompat", "Query Uri: $allowContentUri err : ${ex.message}")
            } finally {
                cursor?.close()
            }

            if (checkNext) {
                try {
                    cursor = context.contentResolver.query(
                        floatContentUri,
                        floatProjection,
                        selection,
                        selectionArgs,
                        null
                    )
                    if (cursor?.moveToFirst() == true) {
                        checkNext = false
                        allowMode = cursor.getInt(0)
                    } else {
                        checkNext = true
                    }
                } catch (ex: Exception) {
                    checkNext = true
                    Log.i("SettingsCompat", "Query Uri: $allowContentUri err : ${ex.message}")
                } finally {
                    cursor?.close()
                }
            } else {
                return allowMode == 0
            }

            return if (checkNext) {
                Settings.canDrawOverlays(context)
            } else {
                allowMode == 0
            }
        }

        override fun requestPermission(context: Context) {
            // 去应用信息
            val intent = Intent()
            intent.setClassName(
                "com.vivo.permissionmanager",
                "com.vivo.permissionmanager.activity.SoftPermissionDetailActivity"
            )
            intent.action = "secure.intent.action.softPermissionDetail"
            intent.putExtra("packagename", context.packageName)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }
    }

}